package com.scedu.controller;

import com.lly835.bestpay.model.PayResponse;
import com.scedu.dto.OrderDTO;
import com.scedu.enums.ResultEnums;
import com.scedu.exception.SellException;
import com.scedu.service.PayService;
import com.scedu.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/*
支付
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    private  OrderServiceImpl orderService;
    @Autowired
    private PayService payService;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String,Object> map
    ){
        //1.查询订单   Order
        OrderDTO orderDTO= orderService.findOne(orderId);
        if (orderDTO==null){
            log.error("订单不存在，orderid={}",orderId);
            throw  new SellException(ResultEnums.ORDER_NOT_EXIT_ERROR);
        }
        //2.发起支付
         map.put("returnUrl",returnUrl);
        PayResponse payResponse=new PayResponse();

        try {
            payResponse= payService.create(orderDTO);

        }
        catch (RuntimeException e){
            log.error(e.getMessage());
            payResponse.setAppId("123");
            payResponse.setNonceStr("123123");
            payResponse.setTimeStamp("asdf");
            payResponse.setPackAge("prepay_id=u802345jgfjsdfgsdg888");
            payResponse.setPaySign("sdfa");
        }
        map.put("payResponse",payResponse);
        return  new ModelAndView("pay/create",map);
    }

    @PostMapping("/notify")
    public  ModelAndView notify(@RequestBody String notifyData){
        log.info("微信返回信息={}",notifyData);
        payService.notify(notifyData);
        //返回给微信处理结果，不然微信不停的发异步通知
         return new ModelAndView("pay/renotify");
    }
}
